/*
 * @Description: 请求相关hook
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2023-10-14
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2023-11-13
 */

import { onMounted, readonly, ref } from 'vue'

import { useLoading } from './useLoading'

/**
 * 页面初始化完成后请求
 */
export const useMountedAsync = <T, S>(fn: (x: T) => Promise<IBaseResponse<S>>, query: T, defaultValue?: S) => {
  const records = ref<S>()
  if (defaultValue) {
    records.value = defaultValue
  }

  const fetch = useLoading(async () => {
    const { data } = await fn(query)
    records.value = data
  })

  onMounted(async () => {
    fetch.trigger()
  })

  return {
    loading: readonly(fetch.loading),
    records: records,
  }
}
